package com.pfsoft.adapter;

import com.pfsoft.util.ChannelUtil;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Sharable
public class ServerChannelHandlerAdapter extends ChannelHandlerAdapter {
    private static final Logger LOGGER = LoggerFactory.getLogger(ServerChannelHandlerAdapter.class);
    /**
     * 注入请求分排器
     */
//    @Resource
//    private RequestDispatcher dispatcher;
//    private int lossConnectCount = 0;

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        LOGGER.error("{} -> [连接异常] {}通道异常，异常原因：{}", this.getClass().getName(),
                ctx.channel().id(), cause.getMessage());
        ctx.close();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        LOGGER.info("{} -> [服务端记录连接通道建立成功] {}", this.getClass().getName(), ctx.channel().id());
        // 注册通道ctx.channel().
//        AttributeKey<Integer> clientName = AttributeKey.valueOf("clientName");
//        ctx.attr(clientName).set(3);
        ChannelUtil.registerChannel(ctx.channel());
    }

    /**
     * 服务器接收到消息时进行进行的处理
     *
     * @param channelHandlerContext channelHandlerContextchannel
     * @param msg                   msg
     */
    @Override
    public void channelRead(ChannelHandlerContext channelHandlerContext, Object msg) {
        if(msg instanceof String)
        {
            if(((String) msg).startsWith("client---"))
            {
                //将client与通道绑定起来
                ChannelUtil.bind(msg.toString(),channelHandlerContext.channel());
                LOGGER.info("当前客户端通道个数{}",ChannelUtil.getClientChannelSize());
            }
        }

//        if (msg instanceof String) {
//            if ("ping-pong-ping-pong".equals(msg)) {
//                LOGGER.info("{} -> [心跳监测] {}：通道活跃", this.getClass().getName(), channelHandlerContext.channel().id());
//                // 心跳消息
//                lossConnectCount = 0;
//                return;
//            } else {
//                String longText = channelHandlerContext.channel().id().asLongText();
//                String resultKey = ChannelUtil.getResultKey(longText);
//                ChannelUtil.calculateResult(resultKey, msg);
//            }
//        } else if (msg instanceof MethodInvokeMeta) {
//            // 转换为MethodInvokeMeta
//            MethodInvokeMeta invokeMeta = (MethodInvokeMeta) msg;
//            LOGGER.info("{} -> [客户端信息] \n 方法名  - > {} \n 参数列表  -> {} \n " +
//                            "返回值  ->  {} ", this.getClass().getName(), invokeMeta.getMethodName(), invokeMeta.getArgs()
//                    , invokeMeta.getReturnType());
//            // 具体的处理类
//            this.dispatcher.dispatcher(channelHandlerContext, invokeMeta);
//        } else {
//            String longText = channelHandlerContext.channel().id().asLongText();
//            String resultKey = ChannelUtil.getResultKey(longText);
//            ChannelUtil.calculateResult(resultKey, msg);
//        }
    }

    /**
     * 触发器
     *
     * @param channelHandlerContext channelHandlerContext
     * @param evt
     * @throws Exception exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext channelHandlerContext, Object evt) throws Exception {
//        LOGGER.info("{} -> [已经有5秒中没有接收到客户端的消息了]", this.getClass().getName());
//        if (evt instanceof IdleStateEvent) {
//            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
//            if (idleStateEvent.state() == IdleState.READER_IDLE) {
//                lossConnectCount++;
//                if (lossConnectCount > 2) {
//                    LOGGER.info("{} -> [释放不活跃通道] {}", this.getClass().getName(), channelHandlerContext.channel().id());
//                    channelHandlerContext.channel().close();
//                }
//            }
//        } else {
//            super.userEventTriggered(channelHandlerContext, evt);
//        }
    }


}
